<template>
    <div class="chooser-component">
        <ul class="chooser-list">
            <li v-for="(item, index) in selections" :key="item" :title="item.label" :class="{'active':checkActive(index)}" @click="toogleSelct(index)">
                {{ item.label }}
            </li>
        </ul>
    </div>
</template>
<script>
export default {
    props: {
        selections: {
            type: Array,
            default: [
                {
                    label: '藏青色',
                    value: 0
                }
            ]
        }
    },
    data() {
        return {
            nowIndexs: [0]
        }
    },
    methods: {
        /*
        * 切换多选组件的逻辑
        * 用一个数组存放已选中选项的index
        * 每次选中时候，先判断数组中有没有这个index，没有就添加，有就移除掉
        */
        toogleSelct(index) {
            if (this.nowIndexs.indexOf(index) === -1) {
                this.nowIndexs.push(index)
            } else {
                for (let i = 0; i < this.nowIndexs.length; i++) {
                    if (this.nowIndexs[i] == index) {
                        this.nowIndexs.splice(i, 1)
                        break;
                    }
                }
            }
            /**
            nowIndex 存放的是目前被选择的值
            将这些选中的值传出去
             */
            let newArray = [];
            for(let i = 0; i < this.nowIndexs.length; i++) {
                newArray[i] = this.selections[this.nowIndexs[i]]
            }
            this.$emit('on-change', newArray)
        },
        checkActive(index) { // 选中状态的，根据数组中有没有这个index来判断
            return this.nowIndexs.indexOf(index) !== -1
        }
    }
} 
</script>
<style scoped>
.chooser-component {
    position: relative;
    display: inline-block;
}

.chooser-list li {
    display: inline-block;
    border: 1px solid #e3e3e3;
    height: 25px;
    line-height: 25px;
    padding: 0 8px;
    margin-right: 5px;
    border-radius: 3px;
    text-align: center;
    cursor: pointer;
}

.chooser-list li.active {
    border-color: #4fc08d;
    background: #4fc08d;
    color: #fff;
}
</style>

